package apj.demo.message.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import apj.demo.util.JDBCUtil;

/**
 * 获取数据库表数据的条数总和
 */
@WebServlet("/datalen")
public class GetTableDataLength extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String tableName = request.getParameter("tableName");
		int count = getLen(tableName);
		PrintWriter out = response.getWriter();
		out.print(count);
	}
	
	public int getLen(String tableName){
		int pageCount = 0;
		String sql = "select count(*) as count from "+tableName;
		Connection conn = null;
		PreparedStatement prep = null;
		ResultSet rst = null;
		
		try {
			conn = JDBCUtil.getConnection();
			prep = conn.prepareStatement(sql);
			rst = prep.executeQuery();
			
			if(rst.next()){
				pageCount = rst.getInt("count");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return pageCount;
	}

}
